# crawler/registration.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User
from .forms import RegistrationForm
from .models import UserProfile


def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()

            # 处理邀请逻辑
            inviter = None
            # 优先从URL参数获取邀请码
            invite_code = request.GET.get('invite_code')
            if invite_code:
                try:
                    inviter_profile = UserProfile.objects.get(invite_code=invite_code)
                    inviter = inviter_profile
                except UserProfile.DoesNotExist:
                    pass

            # 如果URL没有邀请码，检查表单输入
            if not inviter:
                inviter_code = form.cleaned_data.get('inviter_code')
                if inviter_code:
                    try:
                        inviter_user = User.objects.get(username=inviter_code)
                        inviter = inviter_user.profile
                    except User.DoesNotExist:
                        pass

            # 更新邀请关系
            if inviter:
                UserProfile.objects.filter(user=user).update(inviter=inviter)

            messages.success(request, '注册成功！请登录')
            return redirect('login')
    else:
        # 处理GET请求时过滤无效的"None"字符串
        invite_code = request.GET.get('invite_code')

        # 新增校验：排除"None"字符串的情况
        if invite_code and invite_code.lower() == 'none':
            invite_code = None

        initial = {'inviter_code': ''}
        if invite_code:
            try:
                inviter_profile = UserProfile.objects.get(invite_code=invite_code)
                initial['inviter_code'] = inviter_profile.user.username
            except UserProfile.DoesNotExist:
                pass
        form = RegistrationForm(initial=initial)

    return render(request, 'registration/register.html', {
        'form': form,
        'system_name': '彩票系统'
    })